#!/bin/bash

# 检查是否提供了进程ID
if [ -z "$1" ]; then
    echo "Usage: $0 <pid>"
    exit 1
fi

# 初始化进程ID
current_pid="$1"
echo "Process ID: $current_pid"

# 检查进程是否存在
if ! ps -p "$current_pid" > /dev/null; then
#if ! pidof "$pid" > /dev/null; then
#    echo "存在进程"
#else
    echo "Process with PID $pid does not exist."
    exit 2
fi

ps -fp "$current_pid" |head -1
# 循环直到 PPID 为 0
while true; do
    # 使用 ps 命令打印进程信息
    ps -fp "$current_pid" |tail -1
    
    # 获取该进程的 PPID
    ppid=$(ps -fp "$current_pid" |tail -1 |awk -F' ' '{print $3}' )    
    #ppid=$(ps -o ppid= -p "$current_pid")
    #ppid=$(ps -f -p "$current_pid" -o ppid= 2>/dev/null)
    
    # 检查 PPID 是否为 1
    if [[ "$ppid" -eq 1 ]]; then
        echo "Reached the root process."
        break
    fi
    
    # 将当前进程ID设置为 PPID，以便下一次循环
    current_pid="$ppid"
done

echo "Process ancestry complete."